﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarolLib.Control;
using System.Xml;
using StockMonitor.Helper;
using CarolLib;
using StockMonitor.Configuration;
using System.Threading;

namespace StockMonitor.UserControls
{
    [ModuleContract("F2C07418-7734-4939-AF74-798F48E24C52", "查询(&Q)", "委托查询")]
    public partial class UCEntrustQuery : MdiUserControl
    {
        HsGateway hs = new HsGateway();

        #region Ctor.

        public UCEntrustQuery()
            : base()
        {
            InitializeComponent();
        }

        public UCEntrustQuery(XmlNode node)
            : this()
        {
            InitializeComponent();
        }

        #endregion

        #region MdiUserControl Members

        public override void Onload()
        {
            this.dgvEntrustQ.AutoGenerateColumns = false;
            this.dgvEntrustHistory.AutoGenerateColumns = false;
            ThreadPool.QueueUserWorkItem(o =>
            {
                RefreshTodayEntrusts();
            });
        }

        public override void Unload()
        {
            //ThreadPool.QueueUserWorkItem(o =>
            //{
            //    RefreshTodayEntrusts();
            //});
        }

        #endregion

        #region Event Handlers

        private void btnEntrustQ_Click(object sender, EventArgs e)
        {
            this.dgvEntrustHistory.DataSource = new SortableBindingList<EntrustRecord>(EntrustList.Query(this.dtpBeginDate.Value, this.dtpEndDate.Value.AddDays(-1)));
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(o =>
            {
                RefreshTodayEntrusts();
            });
        }

        private void timeAutoEQ_Tick(object sender, EventArgs e)
        {
            RefreshTodayEntrusts();
        }

        private void cbAutoRefresh_CheckedChanged(object sender, EventArgs e)
        {
            if (cbAutoRefresh.Checked)
            {
                timeAutoEQ.Enabled = true;
                timeAutoEQ.Interval = AppSettings.GetValue<int>("AutoRefreshInterval");
            }
            else
                timeAutoEQ.Enabled = false;
        }

        private void btnWithdraw_Click(object sender, EventArgs e)
        {
            if (!ValidateWithdraw())
                return;

            int entNo = Convert.ToInt32(this.lblEntNo.Text);
            string stockCode = this.dgvEntrustQ.CurrentRow.Cells["col1StockCode"].Value.ToString();

            try
            {
                int result = TradeContext.Instance.WithdrawOrder(entNo, stockCode);
                Log.Info(entNo.ToString() + "撤单操作已提交，撤单委托编号为：" + result.ToString());

                ThreadPool.QueueUserWorkItem(o =>
                {
                    Thread.Sleep(2000);
                    RefreshTodayEntrusts();
                    AuthUserContext.Instance.RefreshBalance();
                });
            }
            catch (HsGateway.HsCommException hsex)
            {
                Log.Exception("交易接口返回错误", hsex);
            }
            catch (Exception ex)
            {
                Log.Exception("系统错误", ex);
            }
        }

        private void dgvEntrustQ_SelectionChanged(object sender, EventArgs e)
        {
            this.btnWithdraw.Visible = false;

            if (dgvEntrustQ.CurrentRow == null)
                return;

            this.lblEntNo.Text = dgvEntrustQ.CurrentRow.Cells["col1EntrustNo"].Value.ToString();

            var ent = TradeContext.Instance.TodayEntrusts.Find(t => t.EntrustNo == int.Parse(this.lblEntNo.Text));
            if (ent == null)
                return;

            var status = ent.EntrustStatus;
            if (status == Enums.EntrustStatus.未报 || status == Enums.EntrustStatus.已报 || status == Enums.EntrustStatus.部成)
            {
                this.btnWithdraw.Visible = true;
                this.btnWithdraw.Tag = this.lblEntNo.Text;
            }
        }

        #endregion

        #region Methods

        private void RefreshTodayEntrusts()
        {
            try
            {
                TradeContext.Instance.TodayEntrusts.UpdateStatus();
            }
            catch (HsGateway.HsCommException hsex)
            {
                Log.Exception("交易接口返回错误", hsex);
            }
            catch (Exception ex)
            {
                Log.Exception("系统错误", ex);
            }

            if (this.lbLastUpdatedTime.InvokeRequired)
            {
                this.Invoke(new Action(UpdateTodayEntrustsUI));
            }
            else
            {
                UpdateTodayEntrustsUI();
            }

        }

        private void UpdateTodayEntrustsUI()
        {

            this.lbLastUpdatedTime.Text = DateTime.Now.ToString("hh:mm:ss");
            var datasource = new SortableBindingList<EntrustRecord>(TradeContext.Instance.TodayEntrusts).Reverse().ToList();
            this.dgvEntrustQ.DataSource = datasource;
            this.dgvEntrustQ.Update();
            this.dgvEntrustQ.Refresh();
        }

        private bool ValidateWithdraw()
        {
            bool confirm = false;
            var ent = TradeContext.Instance.TodayEntrusts.Find(t => t.EntrustNo == Convert.ToInt32(this.lblEntNo.Text));
            if (ent == null)
                return confirm;

            string msg = string.Format("您是否要撤销以下委托：\r\n\r\n合同 {0}: {1} {2}({3}) {4}股", ent.EntrustNo, ent.Entrustbs, ent.StockCode, ent.StockName, ent.EntrustAmount);

            if (MessageBox.Show(msg, "撤单确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
            {
                confirm = true;
            }
            return confirm;
        }

        #endregion
    }
}
